package lab.jsp;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lab.domain.Genre;

/**
 *
 * @author Smike
 */
public class EditGenre extends AbstractJSP<Genre> {

    public static final String ID = "id";
    public static final String NAME = "name";
    Genre genre;

    @Override
    public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // do nothing
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        genre = new Genre();
        String id = request.getParameter(ID);
        if (id != null) {
            genre.setId(Integer.valueOf(id));
        } else {
            genre.setId(-1);
        }
        super.doGet(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        genre = new Genre();
        String id = request.getParameter(ID);
        if (id != null) {
            genre.setId(Integer.valueOf(id));
        } else {
            throw new IllegalArgumentException();
        }
        try {
            if (request.getParameter("save") != null) {
                genre.setName(request.getParameter(NAME));
                if (genre.getId() >= 0) {
                    dao.updateGenre(genre);
                } else {
                    dao.insertGenre(genre);
                }
            } else if (request.getParameter("delete") != null) {
                if (genre.getId() >= 0) {
                    dao.deleteGenre(genre);
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(EditGenre.class.getName()).log(Level.SEVERE, null, ex);
        }
        response.sendRedirect("genres.jsp");
    }

    @Override
    protected Genre getData() {
        Logger.getLogger(EditGenre.class.getName()).severe("id is " + genre.getId());
        if (genre.getId() >= 0) {
            try {
                return (Genre) dao.findGenre(genre.getId());
            } catch (Exception ex) {
                Logger.getLogger(EditGenre.class.getName()).log(Level.SEVERE, null, ex);
                throw new RuntimeException(ex);
            }
        } else {
            return genre;
        }
    }
}
